package com.example.edu.service.impl;

import com.example.edu.entity.Subject;



import com.example.edu.entity.excel.SubjectData;
import com.example.edu.entity.subject.OneSubject;
import com.example.edu.entity.subject.TwoSubject;
import com.example.edu.listener.EasyExcelSubjectListener;
import com.example.edu.mapper.SubjectMapper;
import com.example.edu.service.SubjectService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author 
 * @since 2020-06-29
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

	@Autowired
	private SubjectMapper subjectMapper;
	
	
	@SuppressWarnings("static-access")
	@Override
	public void saveSubject(MultipartFile file,SubjectService subjectService) {
		// TODO Auto-generated method stub
		try {
			EasyExcel.read(file.getInputStream(),SubjectData.class, new EasyExcelSubjectListener(subjectService)).sheet().doRead();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
     
	}

	@Override
	public List<OneSubject> listSubject() {
		/**
		 * 查询一级分类
		 */
		QueryWrapper<Subject> oneWrapper = new QueryWrapper<>();
		
		oneWrapper.eq("parent_id", "0");
		
		List<Subject> oneSubjects = subjectMapper.selectList(oneWrapper);
		/**
		 * 查询二级分类
		 */
		QueryWrapper<Subject> twoWrapper = new QueryWrapper<>();
		
		twoWrapper.ne("parent_id", "0");
		
		List<Subject> twoSubjects = subjectMapper.selectList(twoWrapper);
		System.out.println(twoSubjects);
		
		
		List<OneSubject> finalOneSubjects = new ArrayList<>();
		for (int i = 0; i < oneSubjects.size(); i++) {
			/**
			 * 封装1级分类
			 */
			OneSubject oneSubject = new OneSubject();
			Subject subject1 = oneSubjects.get(i);
			BeanUtils.copyProperties(subject1, oneSubject);
			
			finalOneSubjects.add(oneSubject);
			
			/**
			 * 封装二级分类
			 */
			List<TwoSubject> finalTwoSubjects = new ArrayList<>();
			for (int j = 0; j < twoSubjects.size(); j++) {
				TwoSubject twoSubject = new TwoSubject();
				Subject subject2 = twoSubjects.get(j);
                BeanUtils.copyProperties(subject2, twoSubject);
				if(subject2.getParentId().equals(subject1.getId())) {
					
					finalTwoSubjects.add(twoSubject);
				}
				
			}
			oneSubject.setChildren(finalTwoSubjects);

		}
		
		return finalOneSubjects;
	}
	
	

}
